<template>
    <el-row :gutter="20" class="doc-manager">
        <!-- My Documents -->
        <el-col :span="12" class="left-panel">
            <div class="panel-header">My Documents</div>
            <el-button type="text" size="mini" icon="el-icon-folder-add" @click="createFolder">New Folder</el-button>

            <el-tree ref="docTree" :data="filteredDocumentTree" node-key="name" show-checkbox
                :props="{ label: 'name', children: 'items' }" :default-expand-all="true" class="doc-tree"
                @check="handleSelectDocs" draggable @node-drop="handleFileDrop">
                <span class="tree-node" slot-scope="{ node, data }">
                    <i :class="data.type === 'folder' ? 'el-icon-folder' : 'el-icon-document'" />
                    <span>{{ data.type === 'folder' ? data.name : data.title }}</span>
                </span>

            </el-tree>

            <div class="doc-actions">
                <el-button type="primary" size="mini" icon="el-icon-right" :disabled="selectedDocs.length === 0"
                    @click="moveToWorkspace">Move to Workspace</el-button>
                <el-button type="danger" size="mini" icon="el-icon-delete" :disabled="selectedDocs.length === 0"
                    @click="deleteSelectedDocs">Delete</el-button>
            </div>

            <el-upload class="upload-area" drag action="" multiple :file-list="uploadFileList" :auto-upload="false"
                :on-change="handleFileChange" :on-remove="handleFileRemove">
                <i class="el-icon-upload"></i>
                <div>Click to upload or drag and drop</div>
            </el-upload>

            <el-button type="primary" size="mini" @click="confirmUpload" :disabled="uploadFileList.length === 0">
                上传到文档库
            </el-button>
        </el-col>

        <!-- Workspace -->
        <el-col :span="12" class="right-panel">
            <div class="panel-header">{{ workspace.name }}</div>
            <el-table :data="workspaceDocs" border size="small">
                <el-table-column prop="name" label="Name" />
                <el-table-column width="160" align="center">
                    <template v-slot="scope">
                        <el-button icon="el-icon-delete" type="text" @click="removeFromWorkspace(scope.row)" />
                    </template>
                </el-table-column>
            </el-table>
        </el-col>
    </el-row>
</template>

<script>
import { documentApi } from '../../api/aigc/index';

export default {
    props: {
        workspace: Object
    },
    data() {
        return {
            documentTree: [],
            workspaceDocs: [],
            selectedDocs: [],
            uploadFileList: []
        };
    },
    mounted() {
        this.loadData();
        this.refreshWorkspaceDocuments();
    },
    watch: {
        workspace: {
            handler(newVal) {
                if (newVal && newVal.slug) {
                    this.refreshWorkspaceDocuments();
                }
            },
            immediate: true,
            deep: true
        }
    },
    methods: {
        async loadData() {
            const docRes = await documentApi.getDocuments();
            this.documentTree = [docRes.localFiles];
            this.selectedDocs = [];
        },
        refreshWorkspaceDocuments() {
            if (!this.workspace || !this.workspace.documents) {
                this.workspaceDocs = [];
                return;
            }

            const docs = this.workspace.documents.map(d => {
                const meta = JSON.parse(d.metadata || '{}');
                return {
                    name: meta.title || d.filename,
                    id: meta.id,
                    docpath: d.docpath,
                    ...meta
                };
            });

            this.workspaceDocs = docs;
        },
        handleSelectDocs(data, { checkedNodes }) {
            this.selectedDocs = checkedNodes.filter(n => n.type === 'file');
        },
        handleFileChange(file, fileList) {
            this.uploadFileList = fileList;
        },
        handleFileRemove(file, fileList) {
            this.uploadFileList = fileList;
        },
        async confirmUpload() {
            const tasks = this.uploadFileList.map(async fileWrapper => {
                const formData = new FormData();
                formData.append('file', fileWrapper.raw);
                await documentApi.uploadDocument(formData);
            });

            await Promise.all(tasks);
            this.$message.success('上传成功');
            this.uploadFileList = [];
            this.loadData();
        },
        async deleteSelectedDocs() {
            await Promise.all(
                this.selectedDocs.map(doc => documentApi.deleteDocument({ name: doc.name }))
            );
            this.$message.success('删除成功');
            this.loadData();
        },
        async moveToWorkspace() {
            if (!this.workspace || !this.workspace.slug) {
                this.$message.error('未找到工作区信息');
                return;
            }

            const docPaths = this.selectedDocs.map(doc => `custom-documents/${doc.name}`);

            try {
                await documentApi.updateEmbeddings(this.workspace.slug, { adds: docPaths });
                this.$message.success('已加入知识库');
                this.loadData();
                this.$emit('workspaceChange', this.workspace)
            } catch (error) {
                this.$message.error('加入知识库失败');
                console.error(error);
            }
        },
        async removeFromWorkspace(doc) {
            try {
                await documentApi.updateEmbeddings(this.workspace.slug, { deletes: [doc.docpath] });
                this.$message.success('已解绑知识库');
                this.loadData();
                this.$emit('workspaceChange', this.workspace)
            } catch (error) {
                this.$message.error('解绑失败');
                console.error(error);
            }
        },
        async createFolder() {
            const name = prompt('请输入新文件夹名称：');
            if (!name) return;
            await documentApi.createFolder({ folderName: name });
            this.$message.success('创建成功');
            this.loadData();
        },
        async handleFileDrop(dragNode, dropNode, type) {
            if (!dragNode || !dropNode || dragNode.data.type !== 'file' || dropNode.data.type !== 'folder') {
                return;
            }
            const from = `custom-documents/${dragNode.data.name}`;
            const to = `custom-documents/${dropNode.data.name}/${dragNode.data.name}`;
            await documentApi.moveFiles({ files: [{ from, to }] });
            this.$message.success('文件已移动');
            this.loadData();
        }
    },
    computed: {
        filteredDocumentTree() {
            const workspaceDocNames = new Set(this.workspaceDocs.map(doc => doc.name));

            const filterTree = (node) => {
                if (node.type === 'folder') {
                    const items = (node.items || []).map(filterTree).filter(Boolean);
                    return items.length > 0 ? { ...node, items } : null;
                }

                const fileName = node.title || node.name;  // 确保和 workspace 中 name 对应
                return workspaceDocNames.has(fileName) ? null : node;
            };

            return this.documentTree.map(filterTree).filter(Boolean);
        }

    },
};
</script>

<style scoped>
.doc-manager {
    height: 100%;
}

.panel-header {
    font-weight: bold;
    font-size: 16px;
    margin-bottom: 5px;
}

.doc-tree {
    border: 1px solid #eaeaea;
    border-radius: 5px;
    padding: 10px;
    height: 300px;
    overflow-y: auto;
    margin-bottom: 10px;
}

.tree-node {
    display: flex;
    align-items: center;
    gap: 6px;
}

.doc-actions {
    display: flex;
    gap: 10px;
    margin-bottom: 10px;
}

.upload-area {
    border: 1px dashed #d9d9d9;
    padding: 20px;
    border-radius: 6px;
    text-align: center;
    background: #f5f7fa;
    margin-bottom: 10px;
}

.right-panel .el-table {
    height: 600px;
    overflow-y: auto;
}
.left-panel {
    height: 700px;
    overflow-y: auto;
}
</style>